package com.lagou.social;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CreateTable {
    private static Configuration conf;
    private static Connection conn;

    /**
     * 初始化连接对象
     * @throws IOException
     */
    @Before
    public void init() throws IOException {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","linux121,linux122,linux123");
        conf.set("hbase.zookeeper.property.clientPort","2181");
        conn = ConnectionFactory.createConnection(conf);
    }

    /**
     * 创建fnet表
     * @throws IOException
     */
    @Test
    public void createTable() throws IOException {
        Admin admin = conn.getAdmin();

        HTableDescriptor fnet = new HTableDescriptor(TableName.valueOf("fnet"));
        HColumnDescriptor friends = new HColumnDescriptor(Bytes.toBytes("friends"));
        fnet.addFamily(friends);
        admin.createTable(fnet);
        System.out.println("fnet 创建完成！！！");
    }

    /**
     * 添加数据
     * @throws IOException
     */
    @Test
    public void putData() throws IOException {

        Table fnet = conn.getTable(TableName.valueOf("fnet"));
        List<Put> puts = new ArrayList<>();

        Put uid1 = new Put(Bytes.toBytes("uid1"));
        uid1.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("uid2"),Bytes.toBytes("uid2"));
        uid1.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("uid3"),Bytes.toBytes("uid3"));
        uid1.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("uid4"),Bytes.toBytes("uid4"));

        Put uid2 = new Put(Bytes.toBytes("uid2"));
        uid2.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("uid1"),Bytes.toBytes("uid1"));
        uid2.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("uid3"),Bytes.toBytes("uid3"));
        uid2.addColumn(Bytes.toBytes("friends"),Bytes.toBytes("uid4"),Bytes.toBytes("uid4"));

        puts.add(uid1);
        puts.add(uid2);

        fnet.put(puts);
        System.out.println("数据插入成功！");

        fnet.close();
    }

    /**
     * 关闭连接
     * @throws IOException
     */
    @After
    public void closeResource() throws IOException {
        conn.close();
    }
}
